'use strict';

angular.module('cn.edu.ncepu.login.controller', [])
	/**
	 * 列表页面controller
	 */
  .controller('loginController', ['$scope', '$http', '$location', function($scope, $http, $location) {
	  $scope.username='';
	  $scope.password='';
	  $scope.imageCodeSrc = "/ngsl/imgCode/getSysManageLoginCode";
	  $scope.validateCode = "";
	  $scope.imgCodeChecked = "0";//验证码未验证或验证失败
	  
	  //刷新验证码
	  $scope.flushValidateCode = function(){
		  $("#imgCode").attr("src", "/ngsl/imgCode/getSysManageLoginCode" + "?time=" + new Date());
		  $scope.validateCode = '';
	  };
	  $scope.flushValidateCode();
	  
	  //验证填入的验证码是否正确
	  $scope.checkValidateCode = function(){
		  $http({
				method:"post",
				url:"/ngsl/imgCode/checkimagecode",
				params:{
					"validateCode" : $scope.validateCode
				}
			}).success(
					function(data, status) {
						console.log('1',data);
						if(data.code && data.code == "-1"){
							$scope.imgCodeChecked = "0";
							$scope.errorMsg = data.msg;
							//$scope.flushValidateCode();
						}
						if(data.code == "200"){
							$scope.imgCodeChecked = "1";
							//$scope.flushValidateCode();
							$scope.errorMsg = '';
						}else{
							$scope.imgCodeChecked = "0";
						}
					}).error(function(data, status) {
						console.log("验证码错误！");
						$scope.imgCodeChecked = "0";
						//$scope.flushValidateCode();
						
			});
	  };
	  
	  //登录
	  $scope.login = function(){
		  
		  if($scope.form.username.$error.required){
			  $scope.errorMsg = '请填写用户名！';
			  return;
		  }
		  if($scope.form.password.$error.required){
			  $scope.errorMsg = '请填写密码！';
			  return;
		  }
		  if($scope.validateCode == ''){
			  $scope.errorMsg = '请填写验证码！';
			  return;
		  }
		  if($scope.imgCodeChecked != '1'){
			  $scope.errorMsg = '验证码错误！';
			  return;
		  }
		  if ($scope.form.$valid) {
				$http({
					method : 'post',
					url : '/ngsl/v0/login',
					params : {
						'username': $scope.username,
						'password': $scope.password
					}
				}).success(function(data, status) {
					if(data.code == '200'){
						window.location.href = "/ngsl";
					}else{
						$scope.errorMsg = data.msg;
					}
				}).error(function(data, status) {
					$scope.errorMsg = data.message;
				});
			} 
	  };
	
		
  }]);
